//
//  HEDoctorPrivateSignViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/18.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEDoctorPrivateSignViewController.h"
#import "HXPhotoPicker.h"
#import "HEReportTextViewCell.h"
#import "HEReportTitleInputCell.h"
#import "HEReportSelectCell.h"
#import "HEOrderTitleCell.h"
#import "HEReportTextCell.h"
#import "HEAddPhotoCell.h"
#import "HEDoctorServerComfireViewController.h"
#import "HEBindUserModel.h"

@interface HEDoctorPrivateSignViewController ()<UITableViewDelegate, UITableViewDataSource, HEReportSelectCellDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) NSMutableArray <HEDoctorCommentModel *> *commentList;
@property (nonatomic, strong) UIButton *bottomView;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;
@property (nonatomic, assign) CGFloat topHeight;
@property (nonatomic, strong) NSMutableArray <HEBindUserModel *>*bindUsers;
@property (nonatomic, strong) GDFiterCellModel *userFilterModel;
@property (nonatomic, strong) NSString *selectUserId;

@end

@implementation HEDoctorPrivateSignViewController

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"家庭医生签约";
     
    [self initUI];

    [self getBindUserData];
}

#pragma mark - load data
- (void)getBindUserData {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:[UserManager sharedUserManager].curUserInfo.id forKey:@"gid"];
    
    KWeakSelf
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KgetBindUser parameters:dict success:^(id  _Nonnull responseObject) {
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        [weakSelf.bindUsers addObjectsFromArray:[HEBindUserModel mj_objectArrayWithKeyValuesArray:response.data]];

        UserInfo *user = [UserManager sharedUserManager].curUserInfo;
        HEBindUserModel *ower = [HEBindUserModel new];
        ower.id = user.id;
        ower.realname = user.realname;
        ower.relations = @"本人";
        [weakSelf.bindUsers insertObject:ower atIndex:0];
      
        NSMutableArray *binds = @[].mutableCopy;
        for (HEBindUserModel *model in weakSelf.bindUsers) {
            [binds addObject: [NSString stringWithFormat:@"%@（%@）",model.realname, model.relations]];
        }
        weakSelf.userFilterModel.pickerDataArray = binds;
        [weakSelf.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)loadUserPrivateData:(NSString *)usid {
    self.selectUserId = usid;
    __weak typeof(self) weakself = self;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:usid forKey:@"usid"];
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KprivateDocinfo parameters:dict success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success && response.data != nil) {
            [Dialog toastBottom:@"该用户已签约了医生"];
            weakself.formModel.pd_name = nil;
            weakself.selectUserId = nil;
            [weakself.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        weakself.formModel.pd_name = nil;
        weakself.selectUserId = nil;
        [weakself.tableView reloadData];
    }];
}


#pragma mark - UI

- (void)initNoticeTopView {
    
    NSString *nstr = @"请认真填写病情描述和病例资料，方便医生给您更全面的诊疗建议";
    _topHeight = [nstr heightForFont:DYFont(16) width:KScreenWidth-30] + 30;
    UIView *noticeWarp = [[UIView alloc] initWithFrame: CGRectMake(0, ZXNavBarHeight, KScreenWidth, _topHeight )];
    noticeWarp.backgroundColor = KHexColor(@"E8F2FE");
    [self.view addSubview:noticeWarp];
 
    UILabel *noticeLb = [UILabel new];
    noticeLb.text = @"请认真填写病情描述和病例资料，方便医生给您更全面的诊疗建议";
    noticeLb.textColor = CNavBgColor;
    noticeLb.numberOfLines = 0;
    noticeLb.font = DYFont(16);
    [noticeWarp addSubview:noticeLb];
    
    [noticeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(noticeWarp).mas_offset(10);
        make.left.equalTo(noticeWarp).mas_offset(15);
        make.right.equalTo(noticeWarp).mas_offset(-15);
        make.bottom.equalTo(noticeWarp).mas_offset(-10);
    }]; 
}

- (void)initUI {
    [self initNoticeTopView];

   CGFloat tabbarHeight = 49 + KSafeTabbarHeight;
    CGFloat topEsoff = _topHeight;
   _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight + topEsoff, KScreenWidth, KScreenHeight- ZXNavBarHeight - tabbarHeight - topEsoff) style:UITableViewStyleGrouped];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 20)];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    
   _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
   _tableView.scrollsToTop = YES;
   _tableView.tableFooterView = [[UIView alloc] init];
   
   self.tableView.backgroundColor = KWhiteColor;
   self.tableView.delegate = self;
   self.tableView.dataSource = self;
   [self.view addSubview:self.tableView];
    
    [self initCell];
    [self initTabBarView];
}

- (void)initCell {
   // 总段
   _sections = [NSMutableArray array];
   NSMutableArray *classArr = [NSMutableArray array];
    
    self.formModel.rp_text = @"拍照化验单，检查资料报告单、用药处方单、患处照片。照片仅患者和医生可见，最多9张";
      

   // 签约人
    GDFiterCellModel *userModel = [GDFiterCellModel new];
    userModel.cellKlass = HEReportSelectCell.class;
    userModel.leftTitle = @"签约人";
    userModel.placeHolder = @"选择签约人";
    userModel.pickerType = GDPickerType_String;
    userModel.isHasMustSigns = YES;
    userModel.pickerDataArray = @[];
    userModel.tableKey = @"pd_name";
    _userFilterModel = userModel;
    
    // 上次就诊时间
    GDFiterCellModel *jzsjModel = [GDFiterCellModel new];
    jzsjModel.cellKlass = HEReportSelectCell.class;
    jzsjModel.leftTitle = @"上次就诊时间";
    jzsjModel.pickerType = GDPickerType_Date;
    jzsjModel.pickerDateType = BRDatePickerModeYMD;
    jzsjModel.tableKey = @"pd_scjzTime";
    jzsjModel.maxDate = [NSDate date];


    // 就诊医院
     GDFiterCellModel *hspModel = [GDFiterCellModel new];
    hspModel.cellKlass = HEReportTitleInputCell.class;
    hspModel.leftTitle = @"就诊医院";
    hspModel.placeHolder = @"请输入就诊医院";
    hspModel.tableKey = @"pd_jzHsp";

    // 就诊科室
    GDFiterCellModel *deptModel = [GDFiterCellModel new];
    deptModel.cellKlass = HEReportTitleInputCell.class;
    deptModel.leftTitle = @"就诊科室";
    deptModel.placeHolder = @"请输入就诊科室";
    deptModel.tableKey = @"pd_jzDept";

    
    // 就诊疾病
     GDFiterCellModel *jbModel = [GDFiterCellModel new];
    jbModel.cellKlass = HEReportTitleInputCell.class;
    jbModel.leftTitle = @"就诊疾病";
    jbModel.placeHolder = @"请输入就诊疾病";
    jbModel.tableKey = @"pd_jzJb";

   // 病情描述
    GDFiterCellModel *bqTitleModel = [GDFiterCellModel new];
    bqTitleModel.cellKlass = HEOrderTitleCell.class;
    bqTitleModel.leftTitle = @"病情描述";
    bqTitleModel.isHasMustSigns = YES;

    // textview
     GDFiterCellModel *textViewModel = [GDFiterCellModel new];
    textViewModel.cellType = GDFiterCellTypeSelect_TEXTView;
    textViewModel.cellKlass = HEReportTextViewCell.class;
    textViewModel.placeHolder = @"详细描述您的病情症状，曾经做过的检查、用药情况，目前病情是加重还是缓解，想要获得医生的什么帮助";
    textViewModel.cellHeight = 250;
    textViewModel.tableKey = @"pd_desc";

    // 病例资料
     GDFiterCellModel *blTitleModel = [GDFiterCellModel new];
    blTitleModel.cellKlass = HEOrderTitleCell.class;
    blTitleModel.leftTitle = @"病例资料";
    
    GDFiterCellModel *noticeModel = [GDFiterCellModel new];
    noticeModel.cellKlass = HEReportTextCell.class;
    noticeModel.tableKey = @"rp_text";
    
    // 上传照片
     GDFiterCellModel *photoModel = [GDFiterCellModel new];
    photoModel.cellKlass = HEAddPhotoCell.class;
    photoModel.cellType = GDFiterCellTypeSelect_ADDPHOTO;
    photoModel.cellHeight = 108;
    
    
    NSMutableArray *secs1 = @[userModel, jzsjModel, hspModel, deptModel, jbModel].mutableCopy;
    NSMutableArray *secs2 = @[bqTitleModel, textViewModel].mutableCopy;
    NSMutableArray *secs3 = @[blTitleModel, noticeModel, photoModel].mutableCopy;
     
    [_sections addObject: secs1];
    [_sections addObject: secs2];
    [_sections addObject: secs3];

   // 添加的时候注意顺序，暂未对顺序做处理
   classArr = @[userModel, jzsjModel, hspModel, deptModel, jbModel, bqTitleModel, textViewModel, blTitleModel, noticeModel, photoModel].mutableCopy;
   [self.tableView mc_registerCellByFiterModels:classArr];
 
   [_tableView reloadData];
}

- (void)initTabBarView {
    UIButton *bottomView = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomView = bottomView;
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = CNavBgColor;
    _bottomView.titleLabel.font = DYBlodFont(18);
    [bottomView setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [bottomView addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView setTitle:[NSString stringWithFormat:@"去签约￥%@", [NSDecimalNumber rounding:_selectServerModel.price afterPoint:2]] forState:UIControlStateNormal];

    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_offset(49);
        make.bottom.offset(-ZXSafeAreaBottom);
    }];
}

- (void)submit {
    
//    if ([DYTools isBlankString:self.formModel.pd_scjzTime]) {
//        [Dialog toastBottom:@"请选择上次就诊时间!"];
//        return;
//    }
//
//    if ([DYTools isBlankString:self.formModel.pd_jzHsp]) {
//        [Dialog toastBottom:@"请输入就诊医院"];
//        return;
//    }
//
//    if ([DYTools isBlankString:self.formModel.pd_jzDept]) {
//        [Dialog toastBottom:@"请输入就诊科室"];
//        return;
//    }
//
//    if ([DYTools isBlankString:self.formModel.pd_jzJb]) {
//        [Dialog toastBottom:@"请输入就诊疾病"];
//        return;
//    }
    
    if ([DYTools isBlankString:self.selectUserId]) {
        [Dialog toastBottom:@"请选择签约人"];
        return;
    }
    if ([DYTools isBlankString:self.formModel.pd_desc]) {
        [Dialog toastBottom:@"请输入病情描述"];
        return;
    }

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        self.group = dispatch_group_create();
        
        // 上传图片
        [self uploadImage: self.formModel];
        
        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(self.group, queue, ^{
            [self createSubmitRequest];
        });
    });
}

- (void)createSubmitRequest {
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:_userModel.user_id forKey:@"doctor_id"];
    [params setValue:_formModel.pd_jzJb forKey:@"disease"];
    [params setValue:_selectServerModel.attr_name forKey:@"service_length"];
    [params setValue:_formModel.pd_jzDept forKey:@"visit_dept"];
    [params setValue:_formModel.pd_desc forKey:@"disease_desc"];
    [params setValue:_formModel.pd_scjzTime forKey:@"last_time"];
    [params setValue:[UserManager sharedUserManager].curUserInfo.realname forKey:@"user_name"];
    [params setValue:_formModel.pd_jzHsp forKey:@"visit_hospital"];
    [params setValue:_userModel.realname forKey:@"doctor_name"];
    [params setValue:self.selectUserId forKey:@"usid"];
    [params setValue:[self.formModel.cm_imgUrls componentsJoinedByString:@","] forKey:@"photo"];
    
    KWeakSelf
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KprviateSave parameters:params success:^(id  _Nonnull responseObject) {

        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            HEDoctorServerComfireViewController *vc = [HEDoctorServerComfireViewController new];
            
            HEServerComfireModel *comfireModel = [HEServerComfireModel new];
            comfireModel.icon_url = weakSelf.userModel.avatar;
            comfireModel.topStr = weakSelf.userModel.realname;
            comfireModel.middleStr = weakSelf.userModel.KDeptStr;
            comfireModel.bottomStr = weakSelf.userModel.hospital_name;
            comfireModel.payParams = @[weakSelf.selectServerModel.server_name,
                                       [NSString stringWithFormat:@"￥%@%@", [NSDecimalNumber rounding:weakSelf.selectServerModel.price afterPoint:2], weakSelf.selectServerModel.unit],
                                       weakSelf.formModel.pd_name
                                        ];
            
            HECreateOrderRequest *request = [HECreateOrderRequest new];
            request.orderType = HEOrderTypeGeneral;
            request.doctor_id = weakSelf.userModel.user_id;
            request.total = 1;
            request.goodsId = weakSelf.selectServerModel.goods_id;
            request.channel = weakSelf.selectServerModel.channel;
            request.skuId = weakSelf.selectServerModel.attr_id;
            request.source = HEOrderSourceTypeiOS;
            request.type = HESubmitPreviewTypeByGoodsDetails;
            request.memberId = weakSelf.selectUserId;
            request.appSource = KAppSource;
        
            HEExtraDoctorInfoModel *extra = [HEExtraDoctorInfoModel new];
            extra.planId = 0;
            extra.order_type = weakSelf.selectServerModel.channel;
            extra.private_doctor_form_id = response.data;
        
            extra.doctor_info = [DoctorInfo new];
            extra.doctor_info.user_id = weakSelf.userModel.user_id;
            extra.doctor_info.post_name = weakSelf.userModel.post_name;
            extra.doctor_info.avatar = weakSelf.userModel.avatar;
            extra.doctor_info.depart_name = weakSelf.userModel.depart_name;
            extra.doctor_info.realname = weakSelf.userModel.realname;
            request.extras = [extra mj_JSONString];
            
            vc.comfireModel = comfireModel;
            vc.orderRequest = request;
            vc.price = weakSelf.selectServerModel.price;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }

    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)uploadImage:(GDFormModel *)model {
    dispatch_group_enter(_group);
    model.cm_imgUrls = @[].mutableCopy;

    if (!(model.cm_imgs.count > 0)) {
        dispatch_group_leave(self.group);
        return;
    }
    
    [WOAFNetWorkingHandle uploadImagesWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil images:model.cm_imgs fileNames:nil imageScale:0.8 imageType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        

    } success:^(id  _Nonnull responseObject) {
        
        HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];

        NSArray *array = [response.data.src componentsSeparatedByString:@","];
        for (NSString *url in array) {
            if (![DYTools isBlankString:url]) {
                [model.cm_imgUrls addObject:url];
            }
        }
        dispatch_group_leave(self.group);

    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(self.group);
    }];
}

  

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   NSMutableArray *sec = _sections[section];
   return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSMutableArray *sec = _sections[indexPath.section];
   GDFiterCellModel *fiterModel = sec[indexPath.row];
   
   UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
   cell.selectionStyle = UITableViewCellSelectionStyleNone;
   fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
   return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  NSMutableArray *sec = _sections[indexPath.section];
   GDFiterCellModel *fiterModel = sec[indexPath.row];

    if (fiterModel.cellType == GDFiterCellTypeSelect_ADDPHOTO ||
        fiterModel.cellType == GDFiterCellTypeSelect_TEXTView) {
        return fiterModel.cellHeight;
    }
   return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
              [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
   }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    GDFiterCellModel *fiterModel = sec.lastObject;
    
    if (section == 0) {
        return CGFLOAT_MIN;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = CViewBgColor;
    return v;
}
 

#pragma mark - UITableViewDelegate
  
- (void)changeTabbarView {
 
}

#pragma mark - HEReportSelectCellDelegate
- (void)cellSelectHandler:(HEReportSelectCell *)cell index:(NSInteger)index {
    [self loadUserPrivateData: self.bindUsers[index].id];
}

#pragma mark -
- (NSMutableArray <HEBindUserModel *> *)bindUsers {
    if (!_bindUsers) {
        _bindUsers = @[].mutableCopy;
    }
    return _bindUsers;
}

@end
